package com.aivin.buildsrc.tool;

import com.aivin.buildsrc.bean.Md5SaveBean;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.Map;

public class CalcMD5 {
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public static void getAllFiles(String strPath ,Map<String ,Md5SaveBean> md5Info) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    getAllFiles(file.getAbsolutePath() ,md5Info);

                } else {
                    if(file.getAbsolutePath().contains("build")){
                        continue;
                    }

                    if(file.getAbsolutePath().contains(".gitignore")){
                        continue;
                    }

                    if(file.getAbsolutePath().contains("proguard-rules.pro")){
                        continue;
                    }

                    String md5 = calcMD5(file);
                    boolean hasContain = md5Info.containsKey(md5) ;
                    if(hasContain){
                        Md5SaveBean bean = md5Info.get(md5) ;
                        bean.count =bean.count+1 ;
                        bean.name=bean.name +"\r\n"+file.getAbsolutePath();
                        md5Info.put( md5 , bean ) ;
                    }else{
                        md5Info.put( md5 , new Md5SaveBean("\r\n"+file.getAbsolutePath() ,1) ) ;
                    }
                }
            }
        }
    }


    private static String calcMD5(File file) {
        try (InputStream stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buf = new byte[8192];
            int len;
            while ((len = stream.read(buf)) > 0) {
                digest.update(buf, 0, len);
            }
            return toHexString(digest.digest());
        } catch (Exception e) {
            WkLog.showMsg("find error="+e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

    private static String toHexString(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

}